<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;
use Illuminate\Support\Facades\DB;
use App\Model\{Admin,User,Config,Cash,Alipay,Wxpay};
use Illuminate\Support\Facades\Redis;

/**
 * @menu_cat 微信提现
 * @icon sunglasses
 * @sort 0
 */
class CashController extends AdminController{
	public $size = 20;
	public function __invoke(){
		return $this->index(func_get_args());
	}

	

	public function ajax_accept($id){
		$param = request()->only(['msg','table']);
		if(isset($param['table']) && $param['table']=='txdata'){
			$bool = DB::table('txdata')->where('id',$id)->update(['state'=>3]);
			return response()->json([
			    'status' => $bool?1:0,
			    'info'=>$bool?'success':'error',
			]);	
		}else{
			$bool = DB::table('partner_cash')->where('id',$id)->update([
				'state'=>1
			]);
			return response()->json([
			    'status' => $bool?1:0,
			    'info'=>$bool?'success':'error',
			]);	
		}	
	}

	public function ajax_batch_accept(){
		$param = request()->only(['ids','table']);
		$ids = explode(',',$param['ids']);
		if(isset($param['table']) && $param['table']=='txdata'){
			$bool = DB::table('txdata')->whereIn('id',$ids)->update(['state'=>3]);
			return response()->json([
			    'status' => $bool?1:0,
			    'info'=>$bool?'success':'error',
			]);	
		}else{
			$bool = DB::table('partner_cash')->whereIn('id',$ids)->update([
				'state'=>1
			]);
			return response()->json([
			    'status' => $bool?1:0,
			    'info'=>$bool?'success':'error',
			]);	
		}
	}

	/**
	 * 合伙人提现，退回资金
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function ajax_refund($id){
		$param = request()->only(['msg','table']);
		if(isset($param['table']) && $param['table']=='txdata'){
			$bool = User::tx_refund($id);
			return response()->json([
			    'status' => $bool!==false?1:0,
			    'info'=>$bool?'success':'error',
			]);
		}else{
			$bool = User::partner_cash_refund($id,$param['msg']);
			return response()->json([
			    'status' => $bool?1:0,
			    'info'=>$bool?'success':'error',
			]);	
		}	
	}

	/**
	 * @menu 提现申请-待审核
	 * @sort 0
	 * @return [type] [description]
	 */
	public function tx($state=0, $payment_type=1){
		$queue_ids = Redis::lrange('songshu:queue',0,-1);
		$temp = [];
		foreach($queue_ids as $item){
			$item = json_decode($item,true);
			if($item['work_type']==2){
				$temp[] = $item['data']['id'];
			}
		}


		$list = DB::table('txdata')->where('user_status',1)->where('state',$state)->where('payment_type',$payment_type)->whereNotIn('id',$temp)->select('*');
        $this->_search($list, $search);
        
        $total = $list->count();
        $this->_order($list, ['id'=>'desc']);
        

        $list = $list->paginate($this->size,['id']);

        $ids = get_array_keys($list->items(),'id');

        $log_status = in_array($state, [4,5])?0:1;
        $logs = DB::table('wx_tx_order')->select(['tx_id','cause'])->whereIn('tx_id',$ids)->where('stats',$log_status)->get()->toArray();
        $alipaylogs = DB::table('zfb_tx_order')->select(DB::raw("`tx_id`,`message` cause"))->whereIn('tx_id',$ids)->where('status',$log_status)->get()->toArray();
        $logs = arrays_set_key($logs,'tx_id');
        $alipaylogs = arrays_set_key($alipaylogs,'tx_id');
        $logs = array_merge($logs, $alipaylogs);
        $logs = arrays_set_key($logs,'tx_id');
        
        

       	Cash::cash_format($list);
       	$states = Config::get_config_bykey('txdata_state');
       	#dd($state);
        return view('Admin.Cash.tx')->with([
            'list' => $list,
            '_search'=>$search,
            'state'=>$states,
            'total_money'=>DB::table('txdata')->where('state',$state)->where('payment_type',$payment_type)->where('user_status',1)->sum('money'),
            'logs'=>$logs,
            'status'=>$state,
        ]);
	}


	/**
	 * @menu 提现申请-已审核
	 * @sort 0
	 * @return [type] [description]
	 */
	public function tx_accept(){
		$this->size=100;
		return $this->tx(3,1);
	}

	/**
	 * @menu 提现申请-已支付
	 * @sort 0
	 * @return [type] [description]
	 */
	public function tx_paid(){
		return $this->tx(1,1);
	}

	/**
	 * @menu 提现申请-未通过
	 * @sort 0
	 * @return [type] [description]
	 */
	public function tx_refund(){
		return $this->tx(2,1);
	}

	/**
	 * @menu 提现失败-客户端
	 * @sort 0
	 * @return [type] [description]
	 */
	public function tx_client_fail(){
		return $this->tx(4,1);
	}

	/**
	 * @menu 提现失败-用户失败
	 * @sort 0
	 * @return [type] [description]
	 */
	public function tx_user_fail(){
		return $this->tx(5,1);
	}

	/**
	 * @menu 失败后再次拒绝
	 * @sort 0
	 */
	public function tx_double_refund(){
		return $this->tx(6,1);
	}

	/**
	 * @menu 每日提现金额
	 * @sort 0
	 */
	public function everyday() {
		$list = DB::table('wx_tx_order')->select(DB::raw("FROM_UNIXTIME(`add_time` ,'%Y-%m-%d') as ymd,sum(money) money"))->where([
			['stats','=',1],
			['money','<>',1]
		])->groupBy('ymd')->get()->toArray();

		$ones = DB::table('wx_tx_order')->select(DB::raw("FROM_UNIXTIME(`add_time` ,'%Y-%m-%d') as ymd,sum(money) money"))->where([
			['stats','=',1],
			['money','=',1]
		])->groupBy('ymd')->get()->toArray();

		$result = [];
		foreach($list as $item) {
			$result[$item->ymd]['money'] = $item->money;
			$result[$item->ymd]['one'] = 0;
			$result[$item->ymd]['weekend'] = date('w', strtotime($item->ymd));
		}
		foreach($ones as $one) {
			$result[$one->ymd]['one'] = $one->money;
			$result[$one->ymd]['money'] = 0;
			$result[$one->ymd]['weekend'] = date('w', strtotime($item->ymd));
		}
		
		krsort($result);
		return view('Admin.Cash.everyday')->with([
            'list' => $result,
            'title'=>'微信每日提现金额'
        ]);
	}


	/**
	 * @menu 提现申请-待审核
	 * @menu_cat 支付宝提现
	 * @icon sunglasses
	 * @sort 0
	 * @return [type] [description]
	 */
	public function alipay_tx_wait(){
		return $this->tx(0,2);
	}


	/**
	 * @menu 提现申请-已审核
	 * @menu_cat 支付宝提现
	 * @icon sunglasses
	 * @sort 0
	 * @return [type] [description]
	 */
	public function alipay_tx_accept(){
		$this->size = 100;
		return $this->tx(3,2);
	}

	/**
	 * @menu 提现申请-已支付
	 * @menu_cat 支付宝提现
	 * @icon sunglasses
	 * @sort 0
	 * @return [type] [description]
	 */
	public function alipay_tx_paid(){
		return $this->tx(1,2);
	}

	/**
	 * @menu 提现申请-未通过
	 * @menu_cat 支付宝提现
	 * @icon sunglasses
	 * @sort 0
	 * @return [type] [description]
	 */
	public function alipay_tx_refund(){
		return $this->tx(2,2);
	}

	/**
	 * @menu 提现失败-客户端
	 * @menu_cat 支付宝提现
	 * @icon sunglasses
	 * @sort 0
	 * @return [type] [description]
	 */
	public function alipay_tx_client_fail(){
		return $this->tx(4,2);
	}

	/**
	 * @menu 提现失败-用户
	 * @menu_cat 支付宝提现
	 * @icon sunglasses
	 * @sort 0
	 * @return [type] [description]
	 */
	public function alipay_tx_user_fail(){
		return $this->tx(5,2);
	}

	/**
	 * @menu 失败后再次拒绝
	 * @menu_cat 支付宝提现
	 * @icon sunglasses
	 * @sort 0
	 * @return [type] [description]
	 */
	public function alipay_tx_double_refund(){
		return $this->tx(6,2);
	}

	/**
	 * @menu 支付宝每日提现金额
	 * @sort 0
	 */
	public function alipay_everyday() {
		$list = DB::table('zfb_tx_order')->select(DB::raw("FROM_UNIXTIME(`time` ,'%Y-%m-%d') as ymd,sum(money) money"))->where([
			['status','=',1],
			['money','<>',1]
		])->groupBy('ymd')->get()->toArray();

		$ones = DB::table('zfb_tx_order')->select(DB::raw("FROM_UNIXTIME(`time` ,'%Y-%m-%d') as ymd,sum(money) money"))->where([
			['status','=',1],
			['money','=',1]
		])->groupBy('ymd')->get()->toArray();

		$result = [];
		foreach($list as $item) {
			$result[$item->ymd]['money'] = $item->money;
			$result[$item->ymd]['one'] = 0;
			$result[$item->ymd]['weekend'] = date('w', strtotime($item->ymd));
		}
		foreach($ones as $one) {
			$result[$one->ymd]['one'] = $one->money;
			$result[$one->ymd]['money'] = 0;
			$result[$one->ymd]['weekend'] = date('w', strtotime($item->ymd));
		}
		
		krsort($result);
		return view('Admin.Cash.everyday')->with([
            'list' => $result,
            'title'=>'支付宝每日提现金额'
        ]);
	}

	/**
	 * @name 合伙人提现付款
	 * @return [type] [description]
	 */
	public function ajax_parther_tx($id){
		$post = request()->only(['ids']);
		$ids = explode(',', $post['ids']);
        foreach($ids as $id){
        	$data = [
        		'work_type'=>3,
        		'data'=>['id'=>$id]
        	];
        	Redis::rpush('songshu:queue',json_encode($data));
        }

        return response()->json(['status'=>1]);
		/*
		$rs = (new Cash())->wx_pay($id);
		return back()->with('success','付款成功'); 
		dump($rs);exit;
		*/
	}


	/**
	 *  @name 普通用户提现
	 */
	public function ajax_user_tx(){
		$post = request()->only(['ids']);
		#$post['ids'] = '89450,89449,89442,89441,89440,89439,89438,89437,89436,89435,89434,89433,89432,89431,89430,89429,89428,89427,89426';
        $ids = explode(',', $post['ids']);
        foreach($ids as $id){
        	$data = [
        		'work_type'=>2,
        		'data'=>['id'=>$id]
        	];
        	Redis::rpush('songshu:queue',json_encode($data));
        }
        return response()->json(['status'=>1]);

        /*
       	return redirect('cash/ajax_txqueue');

		$rs = (new Cash())->tx($id);
		dd($rs);
		*/
	}


	/**
	 * 普通提现队列
	 */
	public function ajax_txqueue(){
		$ids = Redis::lrange('songshu:queue',0,-1);
		$temp = [];
		$total = 0;
		foreach($ids as $item){
			$item = json_decode($item,true);
			if($item['work_type']==2){
				$temp[] = $item['data']['id'];
				$total++;
			}
		}
		$list = DB::table('txdata')->whereIn('id',$temp)->get()->toArray();
		return view('Admin.Cash.ajax_txqueue')->with([
            'list' => $list,
            'total'=>$total
        ]);
	}

	/**
	 * 合伙人提现队列
	 */
	public function ajax_cashqueue(){
		$ids = Redis::lrange('songshu:queue',0,-1);
		$temp = [];
		$total = 0;
		foreach($ids as $item){
			$item = json_decode($item,true);
			if($item['work_type']==3){
				$temp[] = $item['data']['id'];
				$total++;
			}
			
		}
		$list = DB::table('partner_cash')->whereIn('id',$temp)->get()->toArray();
		return view('Admin.Cash.ajax_cashqueue')->with([
            'list' => $list,
            'total'=>$total
        ]);
	}

	/**
	 * @menu_cat 资金管理
	 * @menu 微信提现查询
	 */
	public function get_wx_info(){
		if(request()->isMethod('post')){
			$model = new Wxpay;

			$param = request()->only(['ids']);
			$ids = explode(',', $param['ids']);
			$list = DB::table('txdata')->whereIn('id',$ids)->get()->toArray();
			foreach($list as $item){
				$result = $model->get_info(['partner_trade_no'=>$item->trad_no]);
				dump([
					'id'=>$item->id,
					'uid'=>$item->uid,
					'real_name'=>$item->real_name,
					'trad_no'=>$item->trad_no,
				]);
				dump($result);
				echo "<hr>";
			}
		}else{
			return view('Admin.Cash.get_wx_info')->with([
	        	
	        ]);
		}	
	}


	public function ajax_pay_info(){
		$result = (new Alipay)->get_info(['out_biz_no'=>'18692020181228']);
		dd($result);
	}


	public function alipay(){
		$p = [];
        $p['out_biz_no'] = '21212121212121212';
        $p['payee_account'] = '602650314@qq.com';
        $p['amount'] = 0.01;
        $p['payee_real_name'] = '吴笛';
        $p['uid'] = 0;

		#$rs = (new Alipay)->pay($p);
		$rs = (new Alipay)->test($p);
		dd($rs);
	}


	/**
	 * @menu 合伙人提现申请
	 * @menu_cat 合伙人提现
	 * @sort -1
	 * @icon sunglasses
	 * @return [type] [description]
	 */
	public function index(){
		$list = DB::table('partner_cash');
        $this->_search($list, $search);
        $total = $list->count();
        $this->_order($list, ['id'=>'desc']);
        
        $list = $list->paginate(20);
       	Cash::cash_format($list);
       	$state = Config::get_config_bykey('cash_state');

       	#dd(DB::table('partner_cash')->where('pay_status',0)->where('state',1)->sum('money'));

        return view('Admin.Cash.index')->with([
            'list' => $list,
            '_search'=>$search,
            'state'=>$state,
            'pay_status'=>Config::get_config_bykey('partner_cash_pay_status'),
            'total_money'=>DB::table('partner_cash')->where('pay_status',0)->where('state',1)->sum('money')
        ]);
	}
}